<!-- 加班 日历 -->
<template>
  <ContainerLayout class="overtime-container">
    <div class="overtime-container-content">
      <template v-if="dataList">
        <el-calendar v-model="valueCalendar" :first-day-of-week="1" :key="forceRerender" class="calendar-warp">
          <template #date-cell="{ data }">
            <OvertimeCalenderCard :date="data.date" :legalList="legalList" :clockinInfo="clockinInfo(data.date)" :item-data="showCalendarCellValue(data.date)" @click="handleClickBtnOpenDialog" @delete="handleClickBtnDelete" />
          </template>
        </el-calendar>
      </template>
    </div>
  </ContainerLayout>
  <DialogOvertime ref="dialogOvertimeInRef" @submit-successed="handleDialogSubmitSuccessed" />
</template>
<script lang="ts" setup>
import ContainerLayout from '../layout/ContainerLayout.vue'
import DialogOvertime from '../components/dialog/DialogOvertime.vue'
import OvertimeCalenderCard from '../components/Overtime/OvertimeCalenderCard.vue'
import { ref, onMounted, watch } from 'vue'
import { useLegalStore, useUsersStore } from '../stores'
import http from '../http'
import { formatDate } from '../utils'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '../api'

const valueCalendar = ref(new Date())
const dialogOvertimeInRef = ref()
const dataList = ref<any>()
const dataClockinList = ref<any>()
const resultList = ref<any[]>([])
const legalList = ref<any[]>([])

const forceRerender = ref(0)
setTimeout(() => {
  forceRerender.value++ // 强制重载组件
}, 1000)
/**
 * 点击按钮打开对话框
 *
 * @param date 日期对象
 */
const handleClickBtnOpenDialog = (val: any) => {
  // console.log('handleClickBtnOpenDialog', val)
  if (!showCalendarCellValue(val.date)) return
  const { mornin, evening } = val.clockinInfo
  if (mornin != '' && evening != '' && dialogOvertimeInRef.value) {
    dialogOvertimeInRef.value.openDialog(val)
  } else {
    ElMessage.warning('请先完成打卡！')
  }
}
/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getOvertimeList = async (currentDate: Date = new Date()) => {
  const currentUser = useUsersStore().getAllState()

  const year = currentDate.getFullYear()
  const month = currentDate.getMonth()
  const start = new Date(year, month, 1)
  const end = new Date(year, month + 1, 0)
  const params = {
    userName: currentUser.username,
    pageSize: 99999,
    startClockinDate: formatDate(start, 'yyyy-MM-dd'),
    endClockinDate: formatDate(end, 'yyyy-MM-dd'),
  }
  // const { rows } = await http({
  //   method: 'GET',
  //   path: '/dev-api/oa/overtime/list',
  //   params,
  // })
  const rows: any[] = await api.Overtime.list(params)
  const result: any = {}
  rows.forEach((row: any) => {
    const key = `${row.overtimeDate}`
    result[key] = {
      ...row,
      // startTime: row.startTime.split(' ')[1],
      // endTime: row.endTime.split(' ')[1],
    }
  })
  // console.log('rows', result)
  dataList.value = result
  resultList.value = rows
  // console.log('resultList.value', resultList.value)
}

/**
 * 获取日历单元格的值
 *
 * @param date 日期对象
 * @returns 返回日期对应的值，如果日期不存在则返回空对象
 */
const showCalendarCellValue = (date: Date) => {
  const key = formatDate(date, 'yyyy-MM-dd')
  const result = dataList.value[key] || {} // 添加默认值 {}
  // console.log('showCalendarCellValue', key, result)
  return result
  // const result = dataList.value[key]
  // if (result) {
  //   return result
  // } else {
  //   return undefined
  // }
}

const handleClickBtnDelete = async (id: number) => {
  ElMessageBox.confirm('确定要删除吗？')
    .then(async () => {
      await http({
        method: 'DELETE',
        path: `/dev-api/oa/overtime/${id}`,
      })
      await getOvertimeList()
    })
    .catch(() => {})
}

const handleDialogSubmitSuccessed = async () => {
  await getOvertimeList()
}
/**
 * 根据日期和类别类型显示打卡信息
 *
 * @param date 日期对象
 * @param categoryType 类别类型，数字类型
 * @returns 打卡时间，如果没有找到则返回空字符串
 */
const showClockinInfoByDate = (date: Date, categoryType: number) => {
  const logDate = formatDate(date, 'yyyy-MM-dd')
  if (dataClockinList.value) {
    const result = dataClockinList.value[`${logDate}-${categoryType}`]
    if (result) {
      return result?.loginTime || ''
    } else {
      return ''
    }
  }
}
/**
 * 获取考勤列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryList = async () => {
  const currentUser = useUsersStore().getAllState()

  const year = valueCalendar.value.getFullYear()
  const month = valueCalendar.value.getMonth()
  const start = new Date(year, month, 1)
  const end = new Date(year, month + 1, 0)
  const params = {
    userName: currentUser.username,
    pageSize: 99999,
    startClockinDate: formatDate(start, 'yyyy-MM-dd'),
    endClockinDate: formatDate(end, 'yyyy-MM-dd'),
  }
  const { rows } = await http({
    method: 'GET',
    path: '/dev-api/oa/clockin/list',
    params,
  })
  const result: any = {}
  rows.forEach((row: any) => {
    const key = `${row.clockinDate}-${row.clockinCategory}`
    result[key] = {
      ...row,
      loginTime: row.clockinTime.split(' ')[1],
    }
  })
  dataClockinList.value = result
  // resultList.value = rows
}
/**
 * 根据给定日期获取上下班打卡信息
 *
 * @param date 日期对象
 * @returns 包含上午和下午打卡信息的对象
 */
const clockinInfo = (date: Date) => {
  const mornin = showClockinInfoByDate(date, 0)
  const evening = showClockinInfoByDate(date, 1)
  return {
    mornin,
    evening,
  }
}
watch(
  () => valueCalendar.value,
  async (newValue) => {
    console.log('newValue', newValue)
    setTimeout(async () => {
      await getOvertimeList(newValue)
      await getClockinCategoryList()
      legalList.value = useLegalStore()
        .getAllState()
        .filter((item) => item.yearNum === newValue.getFullYear())
    }, 200)
  }
)
onMounted(async () => {
  await getOvertimeList()
  await getClockinCategoryList()
  legalList.value = useLegalStore()
    .getAllState()
    .filter((item) => item.yearNum === new Date().getFullYear())
  // legalList.value = await api.Legal.getLegalByYear(new Date().getFullYear())
  // console.log('legalList.value', legalList.value)
})
</script>
<style lang="scss" scoped>
.overtime-container {
  display: flex;
  flex-direction: row;
  .overtime-container-content {
    height: 100%;
    flex: 1;
    .calendar-warp {
      height: 100%;
    }
  }
}
</style>

<style lang="scss"></style>
